interface I {
    events: Map<string, Function[]>
    once: (event: string, callback: Function) => void; // 触发一次
    emit: (event: string, ...args: any[]) => void; // 派发
    on: (event: string, callback: Function) => void; // 订阅
    off: (event: string, callback: Function) => void; // 取消订阅
}
// 发布订阅模式
class Emitter implements I {
    events: Map<string, Function[]>;
    constructor(){
        this.events = new Map();
    }
    once(event: string, callback: Function) {
        // 创建一个自定义函数，通过on触发，然后通过off回收
        const fn = (...args: any[]) => {
            callback(...args);
            this.off(event, fn);
        }
        this.on(event, fn)
    }
    emit(event: string, ...args: any[]) {
        const callbackList = this.events.get(event);
        if (callbackList) {
            callbackList.forEach(fn => fn(...args));
        }
    }
    on(event: string, callback: Function) {
        if (this.events.has(event)) {
            const callbackList = this.events.get(event);
            callbackList && callbackList.push(callback);
        } else {
            this.events.set(event, [callback]);
        }

    }
    off(event: string, callback: Function) {
        if (this.events.has(event)) {
            const callbackList = this.events.get(event);
            callbackList && callbackList.splice(callbackList.indexOf(callback), 1);
        }
    }
} 

const bus = new Emitter();
const fn = (a: number, b: number) => {
    console.log('a', a, 'b', b);
};
bus.on('message', fn);
bus.on('message', (b: boolean, text: string) => {
    console.log('message');
});
bus.off('message', fn)
console.log(bus);

bus.emit('message', true, 'hello');